<template>
  <div class="app-container">
    <el-card>
      <el-page-header @back="goBack">
        <template #content>
          <div class="flex items-center">
            <div v-if="!route.query?.id">新增发货单</div>
            <div v-else>
              <span
                class="text-sm mr-2"
                style="color: var(--el-text-color-regular)"
              >
                发货单编码:
              </span>
              <el-tag>{{ form.code }}</el-tag>
            </div>
          </div>
        </template>
        <template #extra>
          <div class="flex items-center" v-if="!route.query.info">
            <el-button type="primary" @click="submitForm">保 存</el-button>
          </div>
        </template>
      </el-page-header>
    </el-card>
    <el-card style="margin-top: 10px">
      <el-collapse v-model="activeNames">
        <el-collapse-item disabled title="基本信息" name="1">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">基本信息</span>
          </template>
          <div>
            <el-form
              :model="form"
              :rules="rules"
              :disabled="flag"
              ref="userRef"
              label-width="100px"
            >
              <el-row :gutter="20">
                <!-- <el-col :span="8">
                                    <el-form-item label="书刊编码" prop="bookCode">
                                        <el-input
                                            v-model="form.bookCode"
                                            placeholder="请输入书刊编码"
                                            maxlength="18"
                                        />
                                    </el-form-item>
                                </el-col> -->
                <!-- <el-col :span="8">
                                    <el-form-item label="书刊名称" prop="bookName">
                                        <el-input
                                            v-model="form.bookName"
                                            placeholder="请输入书刊名称"
                                        />
                                    </el-form-item>
                                </el-col> -->
                <el-col :span="8">
                  <el-form-item label="发货名称" prop="deliveryName">
                    <el-input
                      v-model="form.deliveryName"
                      placeholder="请输入发货名称"
                    />
                  </el-form-item>
                </el-col>
                <!-- <el-col :span="8">
                                    <el-form-item label="书刊名称" prop="bookName">
                                        <el-input
                                            v-model="form.bookName"
                                            placeholder="请输入书刊名称"
                                        />
                                    </el-form-item>
                                </el-col> -->
                <el-col :span="8">
                  <el-form-item label="发货时间" prop="deliveryDate">
                    <el-date-picker
                      style="width: 100%"
                      v-model="form.deliveryDate"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      type="date"
                      placeholder="请选择时间"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="客户名称" prop="customName">
                    <el-input
                      v-model="form.customName"
                      @click="openDialog"
                      readonly
                      placeholder="请选择客户名称"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="创建人" prop="createBy">
                    <el-input v-model="form.createBy" readonly placeholder="" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="备注">
                    <el-input
                      v-model="form.remark"
                      type="textarea"
                      placeholder="请输入内容"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-collapse-item>
        <el-collapse-item disabled title="发货明细" name="2">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">发货明细</span>
          </template>
          <el-button
            v-if="!flag"
            style="margin-bottom: 10px"
            type="primary"
            size="small"
            @click="handleAddStorage"
          >
            内文生产单
          </el-button>
          <el-table
            v-loading="loading"
            class="table-form"
            :data="deliveryDetailList"
          >
            <el-table-column
              label="序号"
              width="60"
              type="index"
              align="center"
            ></el-table-column>
            <el-table-column
              label="生产单编码"
              align="center"
              width="120"
              prop="produceNo"
            ></el-table-column>
            <el-table-column
              label="发货品种"
              min-width="200"
              align="center"
              prop="productName"
            ></el-table-column>
            <el-table-column
              label="订单数量"
              align="center"
              min-width="120"
              prop="orderCount"
            ></el-table-column>
            <!-- <el-table-column
              label="累计发货量"
              align="center"
              min-width="120"
              prop="deliveryCount"
            ></el-table-column> -->
            <el-table-column label="包数" align="center" prop="packNum">
              <template #default="scope">
                <el-form-item>
                  <el-input-number
                    @blur="changeQuantity(scope.row, scope.$index)"
                    type="number"
                    :min="0"
                    :controls="false"
                    :disabled="flag"
                    v-model.number="scope.row.packNum"
                    placeholder="请输入"
                  ></el-input-number>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="每包数量"
              align="center"
              min-width="120"
              :show-overflow-tooltip="true"
              prop="packInNum"
            >
              <template #default="scope">
                <el-form-item>
                  <el-input-number
                    @blur="changeQuantity(scope.row, scope.$index)"
                    type="number"
                    :min="0"
                    :controls="false"
                    :disabled="flag"
                    v-model.number="scope.row.packInNum"
                    placeholder="请输入"
                  ></el-input-number>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="零数"
              align="center"
              min-width="120"
              :show-overflow-tooltip="true"
              prop="zeroNum"
            >
              <template #default="scope">
                <el-form-item>
                  <el-input-number
                    @blur="changeQuantity(scope.row, scope.$index)"
                    type="number"
                    :min="0"
                    :controls="false"
                    :disabled="flag"
                    v-model.number="scope.row.zeroNum"
                    placeholder="请输入"
                  ></el-input-number>
                </el-form-item>
              </template>
            </el-table-column>
            <!-- 数量=包数*数量/包+零数 -->
            <el-table-column
              label="数量"
              min-width="120"
              align="center"
              prop="quantity"
            >
              <template #default="scope">
                <el-form-item>
                  <el-input-number
                    type="number"
                    :min="0"
                    @change="changeQuantityLing(scope.row)"
                    :controls="false"
                    :disabled="flag"
                    v-model="scope.row.quantity"
                    placeholder="自动计算"
                  ></el-input-number>
                </el-form-item>
              </template>
            </el-table-column>

            <!-- <el-table-column
                            align="center"
                            label="领用数量"
                            min-width="120"
                            prop="useNumber"
                            :show-overflow-tooltip="true"
                        >
                            <template #default="scope">
                                <el-form-item>
                                    <el-input
                                        @input="limitInput('useNumber', scope.row)"
                                        type="number"
                                        :disabled="flag"
                                        v-model.number="scope.row.useNumber"
                                        placeholder="请输入"
                                    ></el-input>
                                </el-form-item>
                            </template>
                        </el-table-column> -->
            <el-table-column
              label="印张"
              width="100"
              align="center"
              prop="sheet"
            >
              <template #default="scope">
                <el-form-item>
                  <el-input
                    type="number"
                    @change="changeQuantityLing(scope.row)"
                    :disabled="flag"
                    v-model="scope.row.sheet"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="用纸令数"
              width="100"
              align="center"
              prop="lingCount"
            />
            <el-table-column
              label="备注"
              width="200"
              align="center"
              prop="remark"
              :show-overflow-tooltip="true"
            >
              <template #default="scope">
                <span v-if="flag">{{ scope.row.remark }}</span>
                <el-form-item v-else>
                  <el-input
                    type="textarea"
                    v-model="scope.row.remark"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              v-if="!flag"
              align="center"
              fixed="right"
              class-name="small-padding fixed-width"
            >
              <template #default="scope">
                <el-tooltip content="删除" placement="top">
                  <el-button
                    link
                    type="primary"
                    icon="Delete"
                    @click="handleDelete(scope.row)"
                  ></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
        <el-collapse-item disabled title="不配套图书管理" name="3">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">不配套图书管理</span>
          </template>
          <div class="order-form">
            <div style="overflow-x: scroll">
              <table
                border="2"
                v-if="listBPT.length > 0"
                cellspacing="0"
                cellpadding="6"
                style="width: 100%"
              >
                <tr>
                  <td class="text" rowspan="2" style="width: 60px">
                    不配套图书
                  </td>
                  <td class="text" style="width: 150px">单号</td>
                  <td
                    class="text"
                    v-for="(item, index) in listBPT"
                    :key="index"
                    width="160"
                  >
                    {{ item.name }}
                  </td>
                </tr>
                <tr>
                  <td class="text">
                    <!-- {{ produceNo }} -->
                    <el-input
                      style="width: 150px"
                      :disabled="flag"
                      v-model="produceNo"
                    ></el-input>
                  </td>
                  <td
                    class="text"
                    v-for="(item, index) in listBPT"
                    :key="index"
                  >
                    <el-input-number
                      type="number"
                      :min="0"
                      :controls="false"
                      :precision="0"
                      :disabled="flag"
                      v-model.number="item.val"
                      placeholder="请输入"
                    ></el-input-number>
                  </td>
                </tr>
              </table>
            </div>
          </div>
        </el-collapse-item>
      </el-collapse>
    </el-card>
    <!-- 发货单明细 -->
    <orderList
      :visible="orderListOpen"
      @changeUpdate="changeOrderData"
      :orderSelectList="orderSelectList"
      @cancel="
        () => {
          orderListOpen = false;
        }
      "
    ></orderList>
    <SearchCustomer
      :visible="visibleCustomer"
      @changeUpdate="changeCustomerData"
      @cancel="
        () => {
          visibleCustomer = false;
        }
      "
    ></SearchCustomer>
  </div>
</template>

<script setup>
import SearchCustomer from "@/components/SearchCustomer";
import orderList from "./orderList.vue";
import { toNumber } from "@/utils/ruoyi";
import { addDeliveryList, getDeliveryById } from "@/api/production/invoice.js";
import useTagsViewStore from "@/store/modules/tagsView";
import useUserStore from "@/store/modules/user";
import { ElMessage } from "element-plus";
import { nextTick } from "vue";
const tagsViewStore = useTagsViewStore();
const { proxy } = getCurrentInstance();
const {
  mes_paper_specs,
  mes_paper_type,
  mes_paper_unit,
  ems_order_breed_type,
} = proxy.useDict(
  "mes_paper_specs",
  "mes_paper_type",
  "mes_paper_unit",
  "ems_order_breed_type"
);
const route = useRoute();
const router = useRouter();
const visibleCustomer = ref(false);
const orderListOpen = ref(false);
const orderSelectList = ref([]);
const listBPT = ref([]); // 不配台图书管理
const produceNo = ref("");
const activeNames = ["1", "2", "3"];
const userRef = ref(null);
const flag = ref(false);
const loading = ref(false);
const userInfo = useUserStore();
const data = reactive({
  form: {},
  deliveryDetailList: [],
  rules: {
    deliveryName: [
      { required: true, message: "发货名称不能为空", trigger: "blur" },
    ],
    // bookCode: [{ required: true, message: '书刊编码不能为空', trigger: 'blur' }],
    customName: [
      { required: true, message: "客户名称不能为空", trigger: "blur" },
    ],
    deliveryDate: [
      {
        required: true,
        message: "发货时间不能为空",
        trigger: ["blur", "change"],
      },
    ],
  },
});

const { form, rules, deliveryDetailList } = toRefs(data);

//限制只能输入4位小数
function limitInput(key, row) {
  row[key] =
    ("" + row[key]) // 第一步：转成字符串
      .replace(/[^\d^\.]+/g, "") // 第二步：把不是数字，不是小数点的过滤掉
      .replace(/^0+(\d)/, "$1") // 第三步：第一位0开头，0后面为数字，则过滤掉，取后面的数字
      .replace(/^\./, "0.") // 第四步：如果输入的第一位为小数点，则替换成 0. 实现自动补全
      .match(/^\d*(\.?\d{0,4})/g)[0] || ""; // 第五步：最终匹配得到结果 以数字开头，只有一个小数点，	而且小数点后面只能有0到2位小数
}
nextTick(() => {
  form.value.createBy = userInfo.name;
  form.value.picker = userInfo.name;
});

if (route.query.id) {
  getDeliveryById({ id: route.query.id }).then((res) => {
    Object.assign(form.value, { ...res.data });
    if (res.data.irregularBooks) {
      const resp = JSON.parse(res.data.irregularBooks);
      listBPT.value = resp.listBPT;
      produceNo.value = resp.produceNo;
    }
    deliveryDetailList.value = res.data.deliveryDetailList;
    if (route.query.info) {
      flag.value = true;
    }
  });
} else {
  flag.value = false;
  form.value = {};
  deliveryDetailList.value = [];
}

// 获取当前时间
const getCurrentDateTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  const hours = String(now.getHours()).padStart(2, "0");
  const minutes = String(now.getMinutes()).padStart(2, "0");
  const seconds = String(now.getSeconds()).padStart(2, "0");
  //   form.value.createTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  form.value.deliveryDate = `${year}-${month}-${day}`;
};
getCurrentDateTime();

// 新增入库明细
const handleAddStorage = () => {
  orderSelectList.value = deliveryDetailList.value;
  orderListOpen.value = true;
};
const findMakeUp = (val) => {
  const foundItem = ems_order_breed_type.value.find(
    (item) => item.value == val
  );
  if (foundItem) {
    return foundItem.label;
  }
};

// // 选中的入库明细
// const changeOrderData = (row, list) => {
//     row.remark = undefined
//     produceNo.value = row.produceNo
//     listBPT.value = []
//     row.breedList.forEach(item => {
//         // listBPT.value.push({ id: row.produceId, name: findMakeUp(item), val: '' })
//         listBPT.value.push({ id: row.produceId, name: item, val: '' })
//     })
//     deliveryDetailList.value = []
//     deliveryDetailList.value.push(row)
//     orderListOpen.value = false
// }
// 获取当前时间
const changeOrderData = (row) => {
  // deliveryDetailList.value = [];
  // listBPT.value = [];
  row.forEach((item, ind) => {
    let isFirst = true;
    (form.value.bookCode = item.produceProductList[0].bookCode),
      (form.value.bookName = item.produceProductList[0].bookName),
      item.produceProductList.forEach((obj, index) => {
        if (isFirst) {
          item.shipmentType += "  " + " " + obj.breed + "+"; // 首次迭代前加空格
          isFirst = false;
        } else {
          item.shipmentType +=
            obj.breed + (index < item.produceProductList.length - 1 ? "+" : "");
        }
      });
    deliveryDetailList.value.push({
      produceId: item.produceId,
      sheet: row[ind].sheet,
      produceNo: item.produceNo,
      productName: item.shipmentType,
      // defaultCount: item.defaultCount,
      // deliveryCount: item.deliveryCount, // 累计发货量
      // productId: item.productId,
      orderCount: item.orderCount,
      remark: item.remark,
    });
    produceNo.value += JSON.parse(item.irregularBooks)?.bookCode
      ? JSON.parse(item.irregularBooks)?.bookCode
      : "";
    JSON.parse(item.irregularBooks).listBPT.forEach((ite) => {
      listBPT.value.push({
        name: ite.name?.split("/")[1],
        val: ite.val,
      });
    });
  });
  orderListOpen.value = false;
};
const changeOrderData1 = (row) => {
  let breedList = [];
  row.produceProductList.forEach((item) => {
    breedList.push(item.breed);
  });
  form.value.productName = row.productName + " " + " " + breedList.join("+");
  (form.value.bookCode = row.produceProductList[0].bookCode),
    (form.value.bookName = row.produceProductList[0].bookName),
    (listBPT.value = []);
  deliveryDetailList.value = [];

  listBPT.value = [];
  let list = JSON.parse(row.irregularBooks);
  produceNo.value = list?.bookCode ? list?.bookCode : "";
  listBPT.value = list.listBPT.map((item) => {
    return {
      name: item.name.split("/")[1],
      val: item.val,
    };
  });
  orderListOpen.value = false;
};

//  数量计算
const changeQuantity = (row, index) => {
  // 数量= 包数*数量/包+零数
  deliveryDetailList.value[index].quantity = toNumber(
    Number(row.packNum || 0) * Number(row.packInNum || 0) +
      Number(row.zeroNum || 0),
    4
  );
  deliveryDetailList.value[index].lingCount = toNumber(
    (Number(row.sheet || 0) * Number(row.quantity || 0)) / 1000,
    2
  );
  // row.deliveryCount = Number(row.defaultCount || 0) + Number(row.quantity || 0);
};
const changeQuantityLing = (row) => {
  row.lingCount = toNumber(
    (Number(row.sheet || 0) * Number(row.quantity || 0)) / 1000,
    2
  );
  // row.deliveryCount = Number(row.defaultCount || 0) + Number(row.quantity || 0);
};
// 删除
const handleDelete = (row) => {
  proxy.$modal.confirm("是否确认删除该数据？").then(function () {
    deliveryDetailList.value = deliveryDetailList.value.filter((item) =>
      item.produceId ? item.produceId != row.produceId : item.id != row.id
    );
    listBPT.value = [];
    proxy.$modal.msgSuccess("删除成功");
  });
};
// 打开机台页面
const openDialog = () => {
  visibleCustomer.value = true;
};
// 选中的机台
const changeCustomerData = (row) => {
  form.value.customName = row.name;
  form.value.customId = row.id;
  visibleCustomer.value = false;
};

// 确认
const submitForm = () => {
  if (deliveryDetailList.value.length <= 0) {
    return ElMessage({
      message: "请选择发货明细",
      type: "warning",
    });
  }
  const invalidItem = deliveryDetailList.value.findIndex(
    (item) => item.quantity <= 0 || !item.quantity
  );

  if (invalidItem !== -1) {
    return ElMessage({
      message: `第${invalidItem + 1}行的发货数量不能小于等于0`,
      type: "warning",
    });
  }
  userRef.value.validate((valid) => {
    if (valid) {
      form.value.irregularBooks = JSON.stringify({
        produceNo: produceNo.value,
        listBPT: listBPT.value,
      });
      if (route.query.id) {
        addDeliveryList({
          ...form.value,
          deliveryDetailList: deliveryDetailList.value,
        }).then((res) => {
          ElMessage({
            message: "编辑成功",
            type: "success",
          });
          goBack();
        });
      } else {
        addDeliveryList({
          ...form.value,
          status: 1,
          deliveryDetailList: deliveryDetailList.value,
        }).then((res) => {
          ElMessage({
            message: "新增成功",
            type: "success",
          });
          goBack();
        });
      }
    }
  });
};
//  返回
const goBack = () => {
  tagsViewStore.delView(route);
  router.go(-1);
  // router.push('/storage/paperAccess')
};
</script>

<style lang="scss" scoped>
.footer {
  text-align: center;
}

:deep(.el-pagination) {
  position: unset;
}

.table-form :deep(.el-form-item) {
  margin-bottom: 0;
}
.text {
  font-weight: 600;
  color: #666262;
}

table,
th,
td {
  border: 1px solid #ccc;
}

th,
td {
  padding: 8px;
  text-align: center;
}

th {
  background-color: #f2f2f2;
}
</style>
